// Problem 051: Prime digit replacements
// By replacing the 1st digit of the 2-digit number *3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
// By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.
// Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.

package main

import (
	"fmt"
	"projecteuler/euler"
)

// p051 Try replace 3 digits of 6-digits primes.
func p051() {
	euler.FillPrime(1000000)
	for _, p := range euler.PrimeList {
		if p < 100000 {
			continue
		}
		if p > 1000000 {
			break
		}
		if a, b := tryThree(p); a == 8 {
			fmt.Println("Prolem 051:", b)
			break
		}
	}
}

func tryThree(n int) (int, int) {
	maxScore, minPrime := 0, n
	digitArr := euler.InDigits(n)
	position := []int{}
	for i := 0; i < len(digitArr)-2; i++ {
		for j := i + 1; j < len(digitArr)-1; j++ {
			if digitArr[i] != digitArr[j] {
				continue
			}
			for k := j + 1; k < len(digitArr); k++ {
				if digitArr[j] == digitArr[k] {
					position = append(position, i, j, k)
				}
			}
		}
		for i := 0; i < len(position)-2; i++ {
			p1, p2, p3 := position[i], position[i+1], position[i+2]
			score := 0
			for d := 0; d < 10; d++ {
				if p1 == 0 && d == 0 {
					continue
				}
				m := digitArr[:]
				m[p1], m[p2], m[p3] = d, d, d
				np := 0
				for _, v := range m {
					np = 10*np + v
				}
				if np > 100000 && euler.IsPrime(np) {
					if np < minPrime {
						minPrime = np
					}
					score++
				}
			}
			if score > maxScore {
				maxScore = score

			}
		}
	}
	return maxScore, minPrime
}
